// 定义 EC11 编码器引脚
const int encoderPinA = 2;  // 编码器引脚A
const int encoderPinB = 3;  // 编码器引脚B
const int buttonPin = 4;    // 编码器按钮引脚

// 变量用于存储编码器状态
volatile int encoderPosition = 0;
volatile int lastEncoderPinAState;
volatile int lastEncoderPinBState;

// 中断处理函数，用于读取编码器状态
void encoderInterrupt() {
  int encoderPinAState = digitalRead(encoderPinA);
  int encoderPinBState = digitalRead(encoderPinB);

  if (encoderPinAState != lastEncoderPinAState) {
    if (encoderPinAState == encoderPinBState) {
      encoderPosition++;
    } else {
      encoderPosition--;
    }
  }

  lastEncoderPinAState = encoderPinAState;
}

void setup() {
  // 设置编码器引脚为输入模式
  pinMode(encoderPinA, INPUT);
  pinMode(encoderPinB, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);

  // 初始化编码器状态
  lastEncoderPinAState = digitalRead(encoderPinA);
  lastEncoderPinBState = digitalRead(encoderPinB);

  // 设置编码器中断
  attachInterrupt(digitalPinToInterrupt(encoderPinA), encoderInterrupt, CHANGE);
}

void loop() {
  // 读取编码器状态
  int currentPosition = encoderPosition;
  bool buttonState = digitalRead(buttonPin);

  // 打印编码器状态
  Serial.print("Encoder Position: ");
  Serial.println(currentPosition);
  Serial.print("Button State: ");
  Serial.println(buttonState);

  delay(100);
}